package com.linln.component.jwt.config;


import com.linln.common.constant.AdminConst;
import com.linln.common.utils.SpringContextUtil;
import com.linln.modules.system.domain.Role;
import com.linln.modules.system.domain.User;
import com.linln.modules.system.service.RoleService;
import org.hibernate.Hibernate;
import org.hibernate.LazyInitializationException;

import java.util.Set;

/**
 * 当前登录用户
 */
public class AuthContext {
    private static final ThreadLocal<User> curUser = new ThreadLocal<>();

    public static void setCurUser(User user) {
        if (user == null) {
            throw new IllegalArgumentException("请指定用户再存储");
        }
        curUser.set(user);
    }

    public static void clear() {
        curUser.remove();
    }

    /**
     * 获取当前用户登录用户的信息
     *
     * @return
     */
    public static User getCurUser() {
        return curUser.get();
    }


    /**
     * 判断当前登录用户是否是管理员
     *
     * @return
     */
    public static boolean isSuperAdmin() {
        Set<Role> roles = getCurUserRoles();
        if (roles == null || roles.isEmpty()) {
            return false;
        }
        for (Role role : roles) {
            if (role == null || role.getId() == null) {
                continue;
            }
            if (role.getId().longValue() == AdminConst.ADMIN_ROLE_ID.longValue()) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取当前用户角色列表
     */
    public static Set<Role> getCurUserRoles() {
        User user = (User) getCurUser();

        // 如果用户为空，则返回空列表
        if (user == null) {
            user = new User();
        }

        // 判断角色列表是否已缓存
        if (!Hibernate.isInitialized(user.getRoles())) {
            try {
                Hibernate.initialize(user.getRoles());
            } catch (LazyInitializationException e) {
                // 延迟加载超时，重新查询角色列表数据
                RoleService roleService = SpringContextUtil.getBean(RoleService.class);
                user.setRoles(roleService.getUserOkRoleList(user.getId()));
            }
        }

        return user.getRoles();
    }
}
